# app/routes/servers.py
from flask import Blueprint, jsonify, request
from app.utils.security import token_required
from app.services.server_service import ServerService
from app.utils.response_utils import (
    success_response,
    error_response,
    ResponseCode
)

# 创建蓝图对象
servers_bp = Blueprint('servers', __name__)


@servers_bp.route('/createServer', methods=['POST'])
@token_required
def create_server(currentUserId):
    """创建新服务器"""
    user_id = currentUserId
    data = request.get_json()
    name = data.get('name')

    if not name:
        return error_response(
            message='服务器名缺失',
            code=ResponseCode.PARAM_ERROR,
            http_code=400
        )

    server = ServerService.create_server(name, user_id)
    if isinstance(server, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message=server[0],
            http_code=server[1]
        )

    return success_response(
        data={
            'server_id': server.server_id,
            'name': server.name,
            'invite_code': server.invite_code
        },
        message='成功创建服务器'
    )

@servers_bp.route('/joinServer', methods=['POST'])
@token_required
def join_server(currentUserId):
    """加入他人服务器"""
    user_id = currentUserId
    data = request.get_json()
    invite_code = data.get('invite_code')

    if not invite_code:
        return error_response(
            message='服务器名缺失',
            code=ResponseCode.PARAM_ERROR,
            http_code=400
        )

    server = ServerService.join_server(user_id, invite_code)
    if isinstance(server, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message=server[0],
            http_code=server[1]
        )

    return success_response(
        data={
            'server_id': server.server_id,
            'name': server.name,
        },
        message='成功加入服务器'
    )

@servers_bp.route('/exitServer', methods=['POST'])
@token_required
def exit_server(currentUserId):
    """加入他人服务器"""
    user_id = currentUserId
    data = request.get_json()
    server_id = data.get('server_id')

    if not server_id:
        return error_response()

    result = ServerService.exit_server(user_id, server_id)
    print(result.get('name'))

    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message=server[0],
            http_code=server[1]
        )

    return success_response(
        data={
            'name': result.get('name'),
        },
        message=f'已退出该{result.get("name")}服务器'
    )

@servers_bp.route('/default', methods=['GET'])
def get_default_server():
    """获取默认服务器信息"""
    server = ServerService.get_default_server()

    if not server:
        return jsonify({'error': 'Default server not found'}), 404

    # 获取服务器下的频道
    channels = server.channels  # 假设Server模型有channels关系

    return jsonify({
        'server_id': server.server_id,
        'name': server.name,
        'channels': [{
            'channel_id': channel.channel_id,
            'name': channel.name,
            'type': channel.type
        } for channel in channels]
    }), 200

@servers_bp.route('/getServerList', methods=['POST'])
@token_required
def get_server_list(currentUserId):
    data = request.get_json()
    userType = data.get('userType')
    # 获取服务器列表
    serverList = ServerService.get_servers_by_user(user_id=currentUserId,userType=userType)

    return success_response(
        data={
            'serverList':serverList,
        },
        message='成功获取服务器列表'
    )

@servers_bp.route('/getChannelList', methods=['POST'])
@token_required
def get_channel_list(currentUserId):
    data = request.get_json()
    server_id = data.get('actServerId')
    # 获取服务器列表
    channelList,memberList = ServerService.get_channel_by_server(server_id=server_id,curUser_id=currentUserId)

    return success_response(
        data={
            'channelList': channelList,
            'memberList': memberList,
        },
        message='成功获取频道列表'
    )

@servers_bp.route('/changeActSC', methods=['POST'])
@token_required
def change_act_sc(currentUserId):
    data = request.get_json()
    server_id = data.get('server_id','')
    channel_id = data.get('channel_id','')
    userType = data.get('userType','')
    # 获取服务器列表

    result = ServerService.change_act_scF(server_id,channel_id,currentUserId,userType)

    return success_response(
        message=result
    )

@servers_bp.route('/getInviteCode', methods=['POST'])
@token_required
def get_invite_code(currentUserId):
    data = request.get_json()
    server_id = data.get('server_id','')
    # 获取服务器邀请码

    result = ServerService.getInviteCode(server_id)
    if result:
        return success_response(
            data={
                'server_id':server_id,
                'invite_code':result
            },
            message=result
        )

@servers_bp.route('/changeServerName', methods=['POST'])
@token_required
def change_server_name(currentUserId):
    data = request.get_json()
    server_id = data.get('server_id','')
    server_name = data.get('server_name','')
    # 获取服务器邀请码
    if not server_name:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='请输入新的服务器名称',
        )
    if not server_id:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='服务器id缺失',
        )

    result = ServerService.changeServerName(server_id,server_name)
    if result:
        return success_response(
            data={
                'server_id':server_id,
                'invite_code':result
            },
            message=result
        )

@servers_bp.route('/createChannel', methods=['POST'])
@token_required
def create_channel(currentUserId):
    data=request.get_json()
    server_id = data.get('server_id')
    type = data.get('type')
    name = data.get('name')
    descripe = data.get('descripe')

    if not server_id or not type or not name:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='参数错误',
        )

    channel = ServerService.addServerChannel(server_id,type,name,currentUserId,descripe)
    if isinstance(channel, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.UNAUTHORIZED,
            message=channel[0],
            http_code=channel[1]
        )

    if channel:
        return success_response(
            data={
                'server_id':server_id,
                'channel_id':channel.channel_id,
                'name':channel.name
            },
            message='成功创建新频道'
        )

@servers_bp.route('/getUserServerInfo', methods=['POST'])
@token_required
def get_user_server_info(currentUserId):
    data = request.get_json()
    server_id = data.get('server_id')
    userType = data.get('userType')

    result = ServerService.getUserServerInfo(currentUserId,server_id,userType)
    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            message=result[0],
            http_code=result[1]
        )


    return success_response(
        data=result,
        message='success'
    )

@servers_bp.route('/getChannelInfo', methods=['POST'])
@token_required
def get_channel_info(currentUserId):
    data=request.get_json()
    channel_id = data.get('channel_id')

    if not channel_id:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='参数错误',
        )

    channel = ServerService.getChannelInfo(channel_id)

    if channel:
        return success_response(
            data=channel
        )

@servers_bp.route('/editChannelInfo', methods=['POST'])
@token_required
def edit_channel_info(currentUserId):
    data=request.get_json()
    name = data.get('name')
    position = data.get('position')
    descripe = data.get('descripe')
    channel_id = data.get('channel_id')

    if not channel_id or not position or not name:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='参数错误',
        )

    position = int(position)

    channel = ServerService.editChannelInfo(channel_id,position,descripe,name,currentUserId)

    if isinstance(channel, tuple):  # 如果是错误响应
        return error_response(
            message=channel[0],
            http_code=channel[1]
        )

    if channel:
        return success_response(
            data=channel
        )


@servers_bp.route('/deleteChannel', methods=['POST'])
@token_required
def delete_channel(currentUserId):
    data = request.get_json()
    channel_id = data.get('channel_id')

    if not channel_id:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='参数错误',
        )

    channel = ServerService.deleteChannel(channel_id,currentUserId)

    if isinstance(channel, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=channel[0],
            http_code=channel[1]
        )

    if channel:
        return success_response(
            message='删除成功'
        )

@servers_bp.route('/getChannelMembers', methods=['POST'])
@token_required
def get_channel_members(currentUserId):
    data = request.get_json()
    channel_id = data.get('channel_id')

    if not channel_id:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='参数错误',
        )

    memberList = ServerService.getChannelMembers(channel_id)

    if isinstance(memberList, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=memberList[0],
            http_code=memberList[1]
        )

    if memberList:
        return success_response(
            data=memberList,
        )

@servers_bp.route('/editMemberPermission', methods=['POST'])
@token_required
def edit_member_permission(currentUserId):
    data = request.get_json()
    member_id = data.get('member_id')
    option = data.get('option')
    value = data.get('value')
    channel_id = data.get('channel_id')

    result = ServerService.editMemberPermission(channel_id=channel_id,member_id=member_id,option=option,value=value,operate_user=currentUserId)

    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=result[0],
            http_code=result[1]
        )

    return success_response(
        message=result,
    )